﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronCow;
using Milkify.Interfaces;
using System.Windows.Input;
using Milkify.Input;
using Milkify.Data;

namespace Milkify.Controllers
{
    public abstract class TaskListListControllerBase : Controller
    {
        private IRefreshableView mView;
        protected IRefreshableView View
        {
            get { return mView; }
        }

        protected TaskListListControllerBase(ControllerContext context, Rtm rtm, IViewContainer viewContainer, IViewFactory viewFactory)
            : base(context, rtm, viewContainer)
        {
            mView = (IRefreshableView)viewFactory.Create("TaskListList");
            mView.Loaded += new System.Windows.RoutedEventHandler(View_Loaded);
            mView.NeedsRefresh = true;
        }

        public override void Execute()
        {
            // Create commands.
            ICommand navigateToTaskListCommand = new DecoupledCommand<object>(NavigateToTaskList);

            // Create view data.
            var viewData = CreateViewData();
            viewData.NavigateToTaskListCommand = navigateToTaskListCommand;
            mView.ViewData = viewData;

            // Change the current view.
            ViewContainer.NavigateToView(mView);
        }

        protected abstract TaskListListViewData CreateViewData();

        private void View_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (mView.NeedsRefresh)
            {
                RefreshLists();
                mView.NeedsRefresh = false;
            }
        }

        private void RefreshLists()
        {
            TaskListListViewData viewData = mView.ViewData as TaskListListViewData;
            if (viewData == null)
                throw new InvalidOperationException("The view data for the task lists view has not been set.");

            viewData.RefreshAsync(Rtm);
        }

        private void NavigateToTaskList(object parameter)
        {
            Redirect("TaskList", "NavigateToTaskList", parameter);
        }

        private void Refresh(object sender, ExecutedRoutedEventArgs e)
        {
            RefreshLists();
            e.Handled = true;
        }
    }
}
